#include "utils_my.h"
#include "stdint.h"
#include "string.h"

uint8_t my_strchrn(const char *str, char ch) {
  uint8_t i = 0, n = 0;

  n = 0;
  for (i = 0; i < strlen(str); i++) {
    if (*(str + i) == ch) {
      n++;
    }
  }
  return n;
}

unsigned char StringDecToHex(char *str, unsigned char *strhex) {
  uint8_t i = 0, j = 0;
  char *p = str;
  uint8_t len = 0;
  uint16_t tmp = 0, mul = 0;

  len = strlen(str);
  if (len > 6) {
    return 1;
  }
  for (i = 0; i < len; i++) {
    if ((*p >= '0') && (*p <= '9')) {
    } else {
      return 2;
    }
  }
  tmp = 0;
  for (i = 0; i < len; i++) {
    mul = 1;
    for (j = 0; j < i; j++) {
      mul *= 10;
    }
    tmp += (*(p + len - 1 - i) - '0') * mul;
  }

  *strhex = tmp & 0xFF;
  *(strhex + 1) = (tmp >> 8) & 0xFF;

  return 0;
}

unsigned char StringToHex(char *str, unsigned char *strhex) {
  uint8_t i = 0, cnt = 0, tmp = 0;
  char *p = str;
  uint8_t len = 0;

  len = strlen(str);
  if (len % 2) {
    return 1;
  }
  for (i = 0; i < len; i++) {
    if (((*p >= '0') && (*p <= '9')) || ((*p >= 'A') && (*p <= 'F')) ||
        ((*p >= 'a') && (*p <= 'f'))) {
    } else {
      return 2;
    }
  }
  cnt = 0;
  while (*p != '\0') {
    if ((*p >= '0') && (*p <= '9')) {
      tmp = *p - '0';
    }
    if ((*p >= 'A') && (*p <= 'F')) {
      tmp = *p - 'A' + 10;
    }
    if ((*p >= 'a') && (*p <= 'f')) {
      tmp = *p - 'a' + 10;
    }
    p++;
    tmp <<= 4;
    if ((*p >= '0') && (*p <= '9')) {
      tmp |= *p - '0';
    }
    if ((*p >= 'A') && (*p <= 'F')) {
      tmp |= *p - 'A' + 10;
    }
    if ((*p >= 'a') && (*p <= 'f')) {
      tmp |= *p - 'a' + 10;
    }
    p++;
    *(strhex + cnt) = tmp;
    cnt++;
  }
  return 0;
}

void utils_line_cal(line_fun_t* line_t) {
  line_t->f32k = ((line_t->point2.f32y - line_t->point1.f32y) /
                  (line_t->point2.f32x - line_t->point1.f32x));
  line_t->f32b = line_t->point1.f32y - (line_t->f32k * line_t->point1.f32x);
  if (line_t->bPositive) {
    line_t->result.f32y = line_t->f32k * line_t->result.f32x + line_t->f32b;
  } else {
    line_t->result.f32x = (line_t->result.f32y - line_t->f32b) / line_t->f32k;
  }
}
